<template>
  <el-dialog title="修改商品" :visible.sync="dialogGoodsSeeVisible" :before-close="cancelDialog" >
    <el-form class="form" :model="dialogGoodsInfo" :rules="formRules" ref="goodsUpdate">

      <el-form-item label="门店名称: " prop="goodName">
        <el-input v-model="dialogGoodsInfo.goodName"></el-input>
      </el-form-item>
      <el-form-item label="门店简介: " prop="description">
        <el-input v-model="dialogGoodsInfo.description"></el-input>
      </el-form-item>
      <el-form-item label="人均消费: " prop="price">
        <el-input v-model.number="dialogGoodsInfo.price" type="number"></el-input>
      </el-form-item>
      <el-form-item label="商品图片: ">
        <br>
        <el-upload
          ref="upload"
          name="img"
          action="http://localhost:8081/goods/update"
          list-type="picture-card"
          :headers="headers"
          :class="{hide:hideUpload}"
          :auto-upload=false
          :limit=limitCount
          :data="this.dialogGoodsInfo"
          :file-list="this.fileList"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleError"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="handleChange">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="updateRequest">确 定</el-button>
      <el-button @click="cancelDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import axios from 'axios'
  import {listByShopId} from '@/api/goods'
  export default {
    name: "GoodsSeeDialog",
    //父组件 传 过来的 值
    props: {
      dialogGoodsSeeVisible: {
        type: Boolean,
        default: false
      },
      dialogGoodsInfo: {
        type: Object,
        default: {}
      },
      fileList:{
        type: Array,
        default:[]
      },
    },
    watch: {
      //监听 弹窗显示， 可以用来写 请求接口
      dialogSeeVisible: function(newVal, oldVal) {
        if (newVal) {

        }
      },
      fileList:function (newVal, oldVal) {
        this.hideUpload = newVal.length >= this.limitCount;
      }
    },
    data() {
      return {
        // 大图
        dialogImageUrl: '',
        limitCount:1,
        // 上传组件+号
        hideUpload: false,
        // 是否已经上替换了文件
        hadUpdateFile: false,
        headers:{Authorization: getToken()},
        dialogVisible: false,
        dialogMapVisible: false,
        formRules: {
          goodName: [{ required: true, message: '请输入商品名称',trigger: 'blur' }],
          description: [{ required: true, message: '请输入商品描述',trigger: 'blur' }],
          price:[
            { required: true, type: 'number', min: 0,message: '请输入价格（最低消费0元）',trigger: 'blur' }
          ],
        },
      };
    },
    computed: {
      // 这里定义上传文件时携带的参数，即表单数据
      upData: function() {
        return this.form
      },

    },
    created() {},
    mounted() {},
    methods: {
      //修改父组件传过来的值
      cancelDialog() {
        this.$emit("update:dialogGoodsSeeVisible", false);
        this.$refs.upload.clearFiles();
      },
      dialogMapVisibles(v){
        this.dialogMapVisible=v;
      },
      updateAddress(v){
        this.form = v
      },
      updateRequest(){
        this.$refs.goodsUpdate.validate((valid) => {
          if(valid){
            if (!this.hadUpdateFile){

                let formData = new FormData();
                Object.keys(this.dialogGoodsInfo).forEach((key) => {
                  formData.append(key, this.dialogGoodsInfo[key]);
                });
                axios({
                url: "http://localhost:8081/goods/update",
                method: "post",
                data: formData,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                  "Authorization": getToken()
                }
                })
                .then(response => {
                  if (response.data.code ===200){
                    this.$message({
                      message: '保存成功',
                      type: 'success'
                    });
                    this.$emit("update:dialogGoodsSeeVisible", false);
                    this.listByShopIdRequest(this.dialogGoodsInfo.shopId);
                  }else{
                    this.$message({
                      message: '未知异常，请联系管理员',
                      type: 'error'
                    });
                  }
                })
                .catch(err => {
                  console.log(err);
                });
            }else{
              this.$refs.upload.submit();
            }
          }
        })
      },
      listByShopIdRequest(id){
        listByShopId(id).then((response) => {
          if(response.code===200){
            this.$emit('update:dialogGoodsInfo',response.data);
          }
        });
      },
      handleRemove(file, fileList) {
        this.hideUpload = fileList.length >= 1;
        console.log(file, fileList);
      },
      handleChange (files, fileList) {
        this.hadUpdateFile = true;
        this.hideUpload = fileList.length >= 1;
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleSuccess(response, file, fileList){
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        // 关闭弹窗
        this.$emit("update:dialogGoodsSeeVisible", false);
        this.listByShopIdRequest(this.dialogGoodsInfo.shopId);
        // 清除上传文件
        this.$refs.upload.clearFiles();
      },
      handleError(err, file, fileList){
        this.$message({
          message: err,
          type: 'success'
        });
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isJPG&&!isPNG) {
          this.$message.error('上传图片只能是 JPG, PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 5MB!');
        }
        return (isJPG||isPNG) && isLt2M;
      },
      showMap(){
        this.dialogMapVisible =true;
      },
    }
  };
</script>

<style lang="scss">
  .form{
    padding: 0 10px;
  }
  .dialog-footer{
    text-align: center;
  }
  .hide .el-upload--picture-card {
    display: none;
  }

</style>
